<?php
/*
 *  avisaro wlan modul 2.0 command line tools
 *  Copyright (C) 2009 Daniel Werner, Mark Schmale
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

class simpleSocket 
{
    protected $fp;

    public function __construct($ip, $port)
    {
        echo 'connecting'.$ip.':'.$port.PHP_EOL;
        $fp = stream_socket_client('tcp://'.$ip.':'.$port, $errno, $errstr);
        if(!$fp) 
        {
            die('Verbindung fehlgeschlagen ('.$errno.': '.$errstr.')'.PHP_EOL);
        } else {
            $this->fp   = $fp;
            $this->ip   = $ip;
            $this->port = $port;
            //stream_set_blocking($this->fp, 0);
        }
    }

    public function writeLine($string)
    {
        $string = trim($string);
        fwrite($this->fp, $string."\n");
    }

    public function write($text)
    {
        $lines = explode("\n", $text);
        foreach($lines as $line)
        {
            if(trim($line) == "") continue;
            $this->writeLine($line);
        }
    }

    public function readByte()
    {
        return fgets($this->fp, 2);
    }

    public function readLine()
    {
        $char = "";
        $line = "";
        do {
          $char  = $this->readByte(); 
          $line .= $char;
        } while($char!="\n");
        return $line;
    }

    public function close()
    {
        fclose($this->fp);
    }
}

?>
